package br.com.news.service.atualiza;

import java.util.List;

import br.com.news.modal.CategoriaBean;
import br.com.news.modal.NoticiaBean;
import br.com.news.service.CategoriaService;
import br.com.news.service.NoticiaService;
import br.com.news.service.interfaces.ICategoriaService;
import br.com.news.service.interfaces.INoticiaService;
import br.com.news.util.Constantes;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class AtualizaNoticiaServico extends Service implements Runnable{

	private INoticiaService noticiaService;
	private ICategoriaService categoriaService;
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		Log.i(Constantes.LOG, "AtualizaNoticiaServico.onCreate");
		noticiaService = new NoticiaService(this);
		categoriaService = new CategoriaService(this);
		new Thread(this).start();
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		noticiaService.fechar();
		categoriaService.fechar();
		Log.i(Constantes.LOG, "AtualizaNoticiaServico.onDestroy");
	}
	
	@Override
	public void run() {
		while (true) {
			try {
				Thread.sleep(15000);
				Log.i(Constantes.LOG, "Inicio da execução do serviço.");
				List<CategoriaBean> categoriaBeans = categoriaService.buscaCategoriasSelecionadas();
				for (CategoriaBean categoriaBean : categoriaBeans) {
					NoticiaBean noticiaBean = noticiaService.buscaUltimaNoticia(categoriaBean.getIdCategoria());
					if (noticiaBean != null) {
						noticiaService.sincronizaUltimasNoticias(noticiaBean.getId(), categoriaBean.getIdCategoria());
					}
				}
				Log.i(Constantes.LOG, "Fim da execução do serviço.");
			} catch (Exception e) {
				Log.i(Constantes.LOG, e.getMessage(), e);
			}
		}
	}

}
